package com.example.wzsdk.scan;

import com.example.wzsdk.callback.onSearchFinsh;
import com.example.wzsdk.commpg.SetPackages;
import com.example.wzsdk.constant.Data;
import com.example.wzsdk.tools.ToolsClass;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;

/**
 * Created by SunLight on 2017/8/11.
 */

public class ScanThread extends Thread {
    private OutputStream outputStream;
    private InputStream inputStream;
    private String ip;
    private SetPackages setPackages;
    private List<ScanSaveEigenValue> scanSaveEigenValueList;
    private int num;
    private onSearchFinsh onSearchFinsh;


    public ScanThread(String ip, int num, List<ScanSaveEigenValue> scanSaveEigenValueList, onSearchFinsh onSearchFinsh, String appId) {
        this.ip = ip;
        this.num = num;
        this.scanSaveEigenValueList = scanSaveEigenValueList;
        this.onSearchFinsh = onSearchFinsh;
        setPackages = new SetPackages();
        ToolsClass.WriteToId(setPackages.getData().AppId, appId);
    }


    @Override
    public void run() {
        Socket socket = null;
        try {
            socket = new Socket(ip, ToolsClass.WZONE_PORT);
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
            outputStream.write(setPackages.ScanPg());
            byte[] s = new byte[1024];
            int i;
            while ((i = inputStream.read(s)) != -1) {
                ScanSaveEigenValue scanSaveEigenValue = new ScanSaveEigenValue();
                System.arraycopy(Arrays.copyOf(s, i), 20, scanSaveEigenValue.getSnHash(), 0, 4);
                System.arraycopy(Arrays.copyOf(s, i), 18, scanSaveEigenValue.getHosttype(), 0, 2);
                scanSaveEigenValue.setSocket(socket);
                scanSaveEigenValueList.add(scanSaveEigenValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (num == 254) {
                onSearchFinsh.onFinsh();
            }
        }
    }
}
